// 引入 express
const express = require("express");
// 引入 bcryptjs
const bcryptjs = require("bcryptjs");
// 引入 jsonwebtoken
const jwt = require("jsonwebtoken");
// 引入 UserModel
const UserModel = require("../models/user");
// 创建 router 实例
const router = express.Router();

router.get("/", (req, res) => {
  res.send("hello express");
});

router.post("/register", async (req, res) => {
  try {
    const doc = await UserModel.findOne({ username: req.body.username });

    if (doc) {
      res.send({
        code: -1,
        msg: "用户名已注册",
      });
      return;
    }

    await UserModel.create({
      ...req.body,
      password: bcryptjs.hashSync(req.body.password, 10),
    });

    res.send({
      code: 0,
      msg: "注册成功",
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: -1,
      msg: "注册失败",
    });
  }
});

router.post("/login", async (req, res) => {
  try {
    const doc = await UserModel.findOne({ username: req.body.username });
    if (!doc) {
      res.send({
        code: -1,
        msg: "用户名不正确",
      });
      return;
    }

    // 校验密码
    const isOk = bcryptjs.compareSync(req.body.password, doc.password);

    if (!isOk) {
      res.send({
        code: -2,
        msg: "密码不正确",
      });
      return;
    }

    // 签发token
    console.log(doc._id.toString());
    const token = jwt.sign(
      {
        _id: doc._id.toString(),
        username: doc.username,
        phone: doc.phone,
      },
      "ABCDEFG",
      { expiresIn: "2h" }
    );

    res.send({
      code: 0,
      msg: "登录成功",
      data: {
        token,
      },
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: -1,
      msg: "登录失败",
    });
  }
});

// 导出 router
module.exports = router;
